package com.hs.chd.action.data;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.app.service.IDataService;
import com.hs.auth.model.HsAccount;
import com.hs.chd.model.SchdFileinfo;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.GlobalParamCache;
import com.hs.core.db.DBMgr;
import com.hs.core.db.QueryPage;
import com.hs.core.utils.SystemUtil;
import com.hs.core.utils.TimeUtil;
import com.hs.core.utils.Tools;
@Controller   
public class ModDataController  extends BaseAction {
    /**
	 * 
	 */
 	private static final Logger logger = Logger.getLogger(ModDataController.class);
	private IDataService dataService;
	@Autowired  
	public void setDataService(IDataService dataService) {
		this.dataService = dataService;
	}
	 /**
	  * 标准数据导入
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/mod/pdfupload.do")   
     public void pdfupload(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 MultipartFile multipartFile = multipartRequest.getFile("pdffile");  
		 //String paperid = multipartRequest.getParameter("paperid");
		 String paperid = request.getParameter("paperid");
		 logger.debug("paperid:" + paperid);
		 logger.debug("String paperid = multipartRequest" +   multipartRequest.getParameter("paperid"));
		 String fileName = multipartFile.getOriginalFilename(); 
		// String webRoot = SystemUtil.getWebappRoot().toString();
		// webRoot = webRoot.replace("\\", "/") + "/temp"; 
		 String sep = System.getProperty("file.separator");
		 sep = "/"; 
//		 File rootDir = new File(webRoot); 
//		 if (!rootDir.exists()) {
//			rootDir.mkdirs(); 
//		 }
		 String sql = "update SCHD_CHNPAPER set ISIMG=1 where id=?";
		 String sql2 = "update SCHD_ENGPAPER set ISIMG=1 where id=?";
		 
		 logger.debug("1");
		 HsAccount acc = this.getCurrentuser(request);
		 String username = acc==null?"":acc.getUserinfo()==null?"":acc.getUserinfo().getUsername();
		 String[] bookinfo = this.writePdfFile(multipartFile.getBytes(), fileName);
		 SchdFileinfo pdffile = new SchdFileinfo();
		 pdffile.setPapercontent(new String(multipartFile.getBytes()));
		 pdffile.setPaperid(new Long(paperid));
		 pdffile.setProdate(TimeUtil.getCurrentDate());
		 logger.debug("2");
		 pdffile.setProuser(username);
		 pdffile.setProversion(1l);
		 pdffile.setPapertitle(fileName);
		 pdffile.setSavepath(bookinfo[0]+bookinfo[1]);
		 this.dataService.saveObject(pdffile);
 		//查询该文献是否已经上传原文
		 DBMgr dbo = this.getDbo(request);
		 dbo.update(sql, new Object[]{paperid});
		 dbo.update(sql2, new Object[]{paperid});
//		 JdbcTemplate jd = dbo.getJdbcTemplate();
//		 logger.debug("begin call auto_refresh_mview_job_proc()");
//		 jd.execute(" call auto_refresh_mview_job_proc()");
//		 logger.debug("end call auto_refresh_mview_job_proc()");
//		 File file = new File(webRoot + sep + fileName);
//		 BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file));
//		 bf.write(multipartFile.getBytes());
//		 bf.close();
		 logger.debug("文件"+fileName+"上传成功!");
		 
		 response.getWriter().write("文件"+fileName+"上传成功!");
	 }
	 private String[] writePdfFile(byte[] fileContent,String fileName) throws Exception{
			String[] temp = new String[3];
			StringBuffer buffer = new StringBuffer();
			String sep = System.getProperty("file.separator");
			sep = "/"; 
			//存储路径
			String webRoot = GlobalParamCache.getInst().getParamByKey("filepath");// SystemUtil.getWebappRoot().getPath() + sep +  "upload";//SWFConvertUtil.getParamMap("filepath");// 
//			if(null != filesavepath)
//				webRoot = filesavepath;
			String middlePath = Tools.buildFileSubdirectory();
			String fileSaveUUID = com.hs.core.utils.UUIDGenerator.getUUID();
			String fullPath = webRoot + sep + middlePath;
			buffer.append(middlePath).append(sep);
			 
			logger.debug("fullPath:" + fullPath);
			File rootDir = new File(webRoot); 
			File directory = null;
			if (!rootDir.exists()) {
				rootDir.mkdirs(); 
			} 
			directory = new File(rootDir, middlePath);
			if(!directory.exists() && !directory.mkdirs()){
				logger.error("创建文件存储路径失败【" + directory.getAbsolutePath() + "】");
			}  
			 
			StringBuffer fileLocation = new StringBuffer(webRoot);
			StringBuffer fileFullPath = new StringBuffer();
			fileLocation.append(middlePath); 
			fileLocation.append(sep); 
			
			fileFullPath.append(middlePath); 
			fileFullPath.append(sep); 
			String fileSaveName = "";
			int pos = fileName.lastIndexOf('.');
			if (pos == -1) {
				fileSaveName = fileSaveUUID;
			} else {
				fileSaveName = fileSaveUUID + fileName.substring(pos);
			}
			//buffer.append(fileSaveName);
			temp[2] = fileLocation.toString();
			fileLocation.append(fileSaveName);
			fileFullPath.append(fileSaveName);
			 
			logger.info("to store file: " + fileLocation);
			File file = new File(fileLocation.toString());
			if(!file.exists()){
				file.createNewFile();
			}
			logger.info("file created!");
			BufferedOutputStream bf = new BufferedOutputStream(
					new FileOutputStream(file));
			bf.write(fileContent);
			bf.close();
			temp[0] = buffer.toString();
			temp[1] = fileSaveName;
			return temp;
		}

	 @RequestMapping("/data/mod/downloadFile.do")   
		public   ModelAndView  downloadFile(HttpServletRequest request,
				HttpServletResponse response, ModelAndView mv) throws Exception {
				Map modelMap = new HashMap();
				String pid = request.getParameter("pid");
			   // response.setCharacterEncoding("UTF-8");
			    DBMgr dbo = DBMgr.getDbUtilInst(request.getSession().getServletContext());
			    List datalist = dbo.queryList("select PAPERTITLE,SAVEPATH from SCHD_FILEINFO where id=(select max(id) from SCHD_FILEINFO where PAPERID=?)", new Object[]{pid});
			    //ChdFileinfo pobj = (ChdFileinfo)dataService.findByID(ChdFileinfo.class, new Long(pid));
				String filePath = GlobalParamCache.getInst().getParamByKey("filepath");
				if(datalist.size()>0){
					Map filedata = (Map)datalist.get(0);
					String fileName = (String)filedata.get("PAPERTITLE");
					String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
		 			logger.debug("ext:" + ext);
	
		 			String fileDbURL = (String)filedata.get("SAVEPATH");
		 			logger.debug("fileDbURL:" + fileDbURL);
		 			filePath += fileDbURL;
					logger.debug("test文件是否存在:" + new File(filePath).exists());
	
		 			filePath = filePath.replace("\\", "/");
		 			logger.debug("fileurl:" + filePath); 
					File file = new File(filePath);
					logger.debug("文件是否存在:" + file.exists());
			       
			        int fileLength = (int)file.length();
			        try{
			        	int                 length   = 0;
				        ServletOutputStream op       = response.getOutputStream();
				        ServletContext      context  = request.getSession().getServletContext();
				        String              mimetype = context.getMimeType( fileName );
				        byte[]   byteContents   =   new   byte[fileLength];   
				        FileInputStream fis   =   new   FileInputStream(file);   
				        int   retcd   =   fis.read(byteContents);   
				        fis.close();    
				        logger.debug("mimetype:" + mimetype);
				        response.setContentType(mimetype == null?"application/pdf":mimetype );
				        response.setContentLength( retcd );
				        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	
				        op.write(byteContents,0,retcd); 
				        op.close();
			            }catch(Exception e){
			            	e.printStackTrace();
			            }
	             }
	            return null;
		}
	 
	
	 /**
	  * 期刊数据管理主页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/mod/dataListFrame.do", method = RequestMethod.GET)   
     public ModelAndView dataListFrame(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		   	
		  return new ModelAndView("app/data/mod/datalistframe",modelMap);
		 
	 }
	 /**
	  * 现代文献数据列表
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/mod/moddatalist.do")   
     public ModelAndView magalist(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 
		 String orderName = request.getParameter("orderName");
		 String orderNum = request.getParameter("orderNum");
		 String startdate = request.getParameter("startdate");
		 String enddate = request.getParameter("enddate");
		 String periodicalname = request.getParameter("periodicalname");
		 String title = request.getParameter("title");
		 String datatype = request.getParameter("datatype");
		 if(null == datatype)
			 datatype = "0";
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		    }else{
		    	orderByStr.append("title").append(" asc");
		    	orderName = "title";
		    	orderNum = "2";
		    }
		 
		 Map conditionmap = new HashMap();
		 StringBuffer sqlbuffer = new StringBuffer();
		 StringBuffer chnsearchBuffer = new StringBuffer(" select * from SCHD_CHNPAPER  where 1=1   ");
		 StringBuffer engsearchBuffer = new StringBuffer(" select * from SCHD_ENGPAPER  where 1=1   "); 

		 StringBuffer conditionbuffer = new StringBuffer();
		 
		 if(StringUtils.isNotBlank(title)){
			String temp = title.trim();
			conditionbuffer.append(" and (title like '%").append(temp).append("%' ");
			conditionbuffer.append(" or titlen like '%").append(temp).append("%') ");
			conditionmap.put("title", temp); 
		 }  
		 if(StringUtils.isNotBlank(startdate)){
			startdate = startdate.replaceAll("-", "");
			conditionbuffer.append(" and to_date(impdate,'yyyy-MM-dd')>=to_date('").append(startdate).append("','yyyy-MM-dd') ");
			conditionmap.put("startdate", startdate);
		 }
		 if(StringUtils.isNotBlank(enddate)){
			enddate = enddate.replaceAll("-", "");
			conditionbuffer.append(" and to_date(impdate,'yyyy-MM-dd')<=to_date('").append(enddate).append("','yyyy-MM-dd')");
			conditionmap.put("enddate", enddate);

		 }
		 if(StringUtils.isNotBlank(periodicalname)){ 
				conditionbuffer.append(" and periodicalname like '%").append(periodicalname).append("%'");
				conditionmap.put("periodicalname", periodicalname);
         } 
		 if("0".equals(datatype)){
			 sqlbuffer.append(chnsearchBuffer);
			 sqlbuffer.append(conditionbuffer);
			 sqlbuffer.append(" union all ");
			 sqlbuffer.append(engsearchBuffer);
			 sqlbuffer.append(conditionbuffer);
		 }else if("1".equals(datatype)){
			 sqlbuffer.append(chnsearchBuffer);
			 sqlbuffer.append(conditionbuffer);
		 }else if("2".equals(datatype)){
			 sqlbuffer.append(engsearchBuffer);
			 sqlbuffer.append(conditionbuffer);
		 }
		 logger.debug("sql:" + sqlbuffer);
		 //sqlbuffer.append(orderByStr);
		 conditionmap.put("orderName", orderName); 
		 conditionmap.put("orderNum", orderNum); 
		 conditionmap.put("startdate", startdate==null?"":startdate); 
		 conditionmap.put("enddate", enddate==null?"":enddate); 
		 conditionmap.put("periodicalname", periodicalname==null?"":periodicalname); 
		 conditionmap.put("title", title==null?"":title.trim());
		 String sql = "select * from ("+sqlbuffer+") "+orderByStr;
	     QueryPage qp = new QueryPage(request,request.getContextPath()+"/data/mod/moddatalist.do",sql,conditionmap); 
		 qp.query();  
		 String pagenum =  qp.getCurrentPageNo() + "";
		 String pagecount = qp.getPerPageCount() + "";
		 modelMap.put("pagenum", pagenum); 
		 modelMap.put("pagecount", pagecount);
		 modelMap.put("pagestr", qp.getPageStr());
		 modelMap.put("datalist", qp.getDataList());  
		 modelMap.put("datatype", datatype);
		 
		 modelMap.put("orderName", orderName);  
		 modelMap.put("orderNum", orderNum); 
		 modelMap.put("startdate", startdate);  
		 modelMap.put("enddate", enddate); 
		 modelMap.put("periodicalname", periodicalname); 
		 modelMap.put("title", title);
	 
		 System.out.println("pageStr:" + qp.getPageStr());
		 return new ModelAndView("app/data/mod/moddatalist",modelMap);
	 }
	 
	 /**
	  * 期刊文献页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/mod/magaimportview.do", method = RequestMethod.GET)   
     public ModelAndView magaimportview(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		   	
		  return new ModelAndView("app/data/mod/magaimportview",modelMap);
		 
	 }
	 
	
	public String getCell(HSSFCell cell){
		if(cell==null)return "";
		switch(cell.getCellType()){
			case HSSFCell.CELL_TYPE_NUMERIC:
				return (long)cell.getNumericCellValue() + "";
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			case HSSFCell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
			case HSSFCell.CELL_TYPE_BLANK:
				return "";
			case	HSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() + "";
			case HSSFCell.CELL_TYPE_ERROR:
	    	    return cell.getErrorCellValue() + "";
	    	default:
	    		return "";
		}
	}
	 /**
	  * 现代文献数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/mod/dataExport.do")   
	public ModelAndView dataExport(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String path = this.exportData("");
			System.out.println("message::" + request.getRequestURL() );
			
           //  path是指欲下载的文件的路径。 
          File file  =   new  File(path);
          String filename  =  file.getName();
         //  取得文件的后缀名。 
           InputStream fis  =   new  BufferedInputStream( new  FileInputStream(path));
           byte [] buffer  =   new   byte [fis.available()];
          fis.read(buffer);
          fis.close();
          response.reset();
         // response.setCharacterEncoding("UTF-8");
          System.out.println("下载文件开始" +   new  String(filename.getBytes("gb2312"),"ISO-8859-1")); 
          response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
          response.addHeader( " Content-Length " ,  ""   +  file.length());
          OutputStream toClient  =   new  BufferedOutputStream(response.getOutputStream());
          response.setContentType( "application/vnd.ms-excel" );
          toClient.write(buffer);
          toClient.flush();
          toClient.close();
      }  catch  (IOException ex) {
          ex.printStackTrace();
      }
		return null;  
	} 
	 /**
	  * 现代文献数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/mod/exportData.do")   
	public ModelAndView exportData(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String ids = request.getParameter("ids");
			if(StringUtils.isEmpty(ids)){
				return null;
			}else{
				ids = ids.substring(0,ids.length()-1);
			}
			String path = this.exportData(ids);
			System.out.println("message::" + path );
			//  path是指欲下载的文件的路径。 
			//response.setCharacterEncoding("UTF-8");
			File file  =   new  File(path);
			String filename  =  file.getName();
			int fileLength = (int)file.length();
			int                 length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = request.getSession().getServletContext();
	        String              mimetype = context.getMimeType( filename );
	        byte[]   byteContents   =   new   byte[fileLength];   
	        FileInputStream fis   =   new   FileInputStream(file);   
	        int   retcd   =   fis.read(byteContents);   
	        fis.close();    
	        logger.debug("mimetype:" + mimetype);
	        response.setContentType(mimetype == null?"application/vnd.ms-excel":mimetype );
	        response.setContentLength( retcd );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	        op.write(byteContents,0,retcd); 
	        op.close();
     }  catch  (IOException ex) {
         ex.printStackTrace();
     }
		return null;  
	} 
	
	/**
	 * 生成题录数据文件
	 * @return 生成的文件的路径
	 */
	public String exportData(String rids){
		String message = "false";
		 try {
				HSSFWorkbook wb = new HSSFWorkbook(); 
				 HSSFSheet sheet = wb.createSheet("new sheet"); 
				 HSSFRow row = sheet.createRow((short)0); 
				 row.createCell(0).setCellValue("分类号");
				 row.createCell(1).setCellValue("中文标题");
				 row.createCell(2).setCellValue("作者");
				 row.createCell(3).setCellValue("作者单位");
				 row.createCell(4).setCellValue("国家\\省市");
				 row.createCell(5).setCellValue("参文数");
				 row.createCell(6).setCellValue("刊名");
				 row.createCell(7).setCellValue("年份");
				 row.createCell(8).setCellValue("卷");
				 row.createCell(9).setCellValue("期");
				 row.createCell(10).setCellValue("页码");
				 row.createCell(11).setCellValue("ISSN编号");
				 row.createCell(12).setCellValue("国内代码");
				 row.createCell(13).setCellValue("内部代码");
				 row.createCell(14).setCellValue("出版地");
				 row.createCell(15).setCellValue("中文关键词");
				 row.createCell(16).setCellValue("中文主题词");
				 row.createCell(17).setCellValue("特征词");
				 row.createCell(18).setCellValue("更新日期");
				 row.createCell(19).setCellValue("英文标题");
				 row.createCell(20).setCellValue("中文摘要");
				 row.createCell(21).setCellValue("著者文摘");
				 row.createCell(22).setCellValue("文献类型");
				 row.createCell(23).setCellValue("基金");
				 row.createCell(24).setCellValue("语种");
				 row.createCell(25).setCellValue("人名主题");
				 row.createCell(26).setCellValue("CA");
				 CellStyle cs=wb.createCellStyle(); 
				 List  accList = DBMgr.getDbUtilInst().queryList("select * from SEARCHMVIEW where id in("+rids+") order by id",null);
				 
				 
				 for(int i=0; i<accList.size(); i++){
						Map data = (Map)accList.get(i);
						HSSFRow onerow = sheet.createRow((short)(i+1)); 
						
						 onerow.createCell(0).setCellValue((String)data.get("CLASSNO")); 
						 onerow.createCell(1).setCellValue((String)data.get("TITLE")); 
						 onerow.createCell(2).setCellValue((String)data.get("AUTHOR")); 
						 onerow.createCell(3).setCellValue((String)data.get("AUTHORUNIT")); 
						 onerow.createCell(4).setCellValue((String)data.get("AREASTR")); 
						 onerow.createCell(5).setCellValue((String)data.get("CWNUM")); 
						 onerow.createCell(6).setCellValue((String)data.get("PERIODICALNAME")); 
						 onerow.createCell(7).setCellValue((String)data.get("YEARSTR")); 
						 onerow.createCell(8).setCellValue((String)data.get("VOLUME")); 
						 onerow.createCell(9).setCellValue((String)data.get("PERIOD")); 
						 onerow.createCell(10).setCellValue((String)data.get("PAGENO")); 
						 onerow.createCell(11).setCellValue((String)data.get("ISSNSTR")); 
						 onerow.createCell(12).setCellValue((String)data.get("CONTRYCODE")); 
						 onerow.createCell(13).setCellValue((String)data.get("CODESTR")); 
						 onerow.createCell(14).setCellValue((String)data.get("PUBLISHAREA")); 
						 onerow.createCell(15).setCellValue((String)data.get("KEYWORD")); 
						 onerow.createCell(16).setCellValue((String)data.get("SUBJECTWORD")); 
						 onerow.createCell(17).setCellValue((String)data.get("IMPRESSWORD")); 
						 onerow.createCell(18).setCellValue((String)data.get("UPDATEDATE")); 
						 onerow.createCell(19).setCellValue((String)data.get("TITLEN"));
						 onerow.createCell(20).setCellValue((String)data.get("ABSTRACT"));
						 onerow.createCell(21).setCellValue((String)data.get("AUTHORABSTRACT")); 
						 onerow.createCell(22).setCellValue((String)data.get("DOCUMENTTYPE")); 
						 onerow.createCell(23).setCellValue((String)data.get("FUNDNAME")); 
						 onerow.createCell(24).setCellValue((String)data.get("LANGUAGE")); 
						 onerow.createCell(25).setCellValue((String)data.get("USERSUBJECT")); 
						 onerow.createCell(26).setCellValue((String)data.get("CASTR"));
 				 }	
				 String tempFilepath = SystemUtil.getWebappRoot().toString();
				 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 System.out.println("tempFilepath::" + tempFilepath );
				 File tempfile = new File(tempFilepath);
				 if(!tempfile.exists()){
					 tempfile.mkdirs();
				 }
				 String destfile = tempFilepath + "/" + "期刊数据.xls";
				 FileOutputStream fileOut = new FileOutputStream(destfile); 
				 wb.write(fileOut); 
				 fileOut.close();
				 message = destfile;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return message;
		
	}
	
	 /**
	  *  数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/mod/exportAllData.do")   
	public ModelAndView exportAllData(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String ids = request.getParameter("ids");
			if(StringUtils.isEmpty(ids)){
				return null;
			}else{
				ids = ids.substring(0,ids.length()-1);
			}
			String path = this.exportTxtData(ids);
			System.out.println("message::" + path );
			//  path是指欲下载的文件的路径。 
			//response.setCharacterEncoding("UTF-8");
			File file  =   new  File(path);
			String filename  =  file.getName();
			int fileLength = (int)file.length();
			int                 length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = request.getSession().getServletContext();
	        String              mimetype = context.getMimeType( filename );
	        byte[]   byteContents   =   new   byte[fileLength];   
	        FileInputStream fis   =   new   FileInputStream(file);   
	        int   retcd   =   fis.read(byteContents);   
	        fis.close();    
	        logger.debug("mimetype:" + mimetype);
	        response.setContentType(mimetype == null?"text/plain":mimetype );
	        response.setContentLength( retcd );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	        op.write(byteContents,0,retcd); 
	        op.close();
    }  catch  (IOException ex) {
        ex.printStackTrace();
    }
		return null;  
	} 
	/**
	 * 生成题录数据文件
	 * @return 生成的文件的路径
	 */
	public String exportAllData(String rids){
		String message = "false";
		 try {
				HSSFWorkbook wb = new HSSFWorkbook(); 
				 HSSFSheet sheet = wb.createSheet("new sheet"); 
				 HSSFRow row = sheet.createRow((short)0); 
				 row.createCell(0).setCellValue("分类号");
				 row.createCell(1).setCellValue("中文标题");
				 row.createCell(2).setCellValue("作者");
				 row.createCell(3).setCellValue("作者单位");
				 row.createCell(4).setCellValue("国家\\省市");
				 row.createCell(5).setCellValue("参文数");
				 row.createCell(6).setCellValue("刊名");
				 row.createCell(7).setCellValue("年份");
				 row.createCell(8).setCellValue("卷");
				 row.createCell(9).setCellValue("期");
				 row.createCell(10).setCellValue("页码");
				 row.createCell(11).setCellValue("ISSN编号");
				 row.createCell(12).setCellValue("国内代码");
				 row.createCell(13).setCellValue("内部代码");
				 row.createCell(14).setCellValue("出版地");
				 row.createCell(15).setCellValue("中文关键词");
				 row.createCell(16).setCellValue("中文主题词");
				 row.createCell(17).setCellValue("特征词");
				 row.createCell(18).setCellValue("更新日期");
				 row.createCell(19).setCellValue("英文标题");
				 row.createCell(20).setCellValue("中文摘要");
				 row.createCell(21).setCellValue("著者文摘");
				 row.createCell(22).setCellValue("文献类型");
				 row.createCell(23).setCellValue("基金");
				 row.createCell(24).setCellValue("语种");
				 row.createCell(25).setCellValue("人名主题");
				 row.createCell(26).setCellValue("CA");
				 row.createCell(27).setCellValue("条目编码");
				 row.createCell(28).setCellValue("书籍名称");
				 row.createCell(29).setCellValue("中医病名");
				 row.createCell(30).setCellValue("原文文本化");
				 row.createCell(31).setCellValue("卷册章节");
				 row.createCell(32).setCellValue("版本");
				 row.createCell(33).setCellValue("录入人");
				 row.createCell(34).setCellValue("录入日期");
				 row.createCell(35).setCellValue("朝代"); 
				 CellStyle cs=wb.createCellStyle(); 
				 List  accList = DBMgr.getDbUtilInst().queryList("select * from CHD_PAPERINFO where id in("+rids+") order by id",null);
				 
				 
				 for(int i=0; i<accList.size(); i++){
						Map data = (Map)accList.get(i);
						HSSFRow onerow = sheet.createRow((short)(i+1)); 
						
						 onerow.createCell(0).setCellValue((String)data.get("CLASSNO")); 
						 onerow.createCell(1).setCellValue((String)data.get("TITLE")); 
						 onerow.createCell(2).setCellValue((String)data.get("AUTHOR")); 
						 onerow.createCell(3).setCellValue((String)data.get("AUTHORUNIT")); 
						 onerow.createCell(4).setCellValue((String)data.get("AREASTR")); 
						 onerow.createCell(5).setCellValue((String)data.get("CWNUM")); 
						 onerow.createCell(6).setCellValue((String)data.get("PERIODICALNAME")); 
						 onerow.createCell(7).setCellValue((String)data.get("YEARSTR")); 
						 onerow.createCell(8).setCellValue((String)data.get("VOLUME")); 
						 onerow.createCell(9).setCellValue((String)data.get("PERIOD")); 
						 onerow.createCell(10).setCellValue((String)data.get("PAGENO")); 
						 onerow.createCell(11).setCellValue((String)data.get("ISSNSTR")); 
						 onerow.createCell(12).setCellValue((String)data.get("CONTRYCODE")); 
						 onerow.createCell(13).setCellValue((String)data.get("CODESTR")); 
						 onerow.createCell(14).setCellValue((String)data.get("PUBLISHAREA")); 
						 onerow.createCell(15).setCellValue((String)data.get("KEYWORD")); 
						 onerow.createCell(16).setCellValue((String)data.get("SUBJECTWORD")); 
						 onerow.createCell(17).setCellValue((String)data.get("IMPRESSWORD")); 
						 onerow.createCell(18).setCellValue((String)data.get("UPDATEDATE")); 
						 onerow.createCell(19).setCellValue((String)data.get("TITLEN"));
						 onerow.createCell(20).setCellValue((String)data.get("ABSTRACT"));
						 onerow.createCell(21).setCellValue((String)data.get("AUTHORABSTRACT")); 
						 onerow.createCell(22).setCellValue((String)data.get("DOCUMENTTYPE")); 
						 onerow.createCell(23).setCellValue((String)data.get("FUNDNAME")); 
						 onerow.createCell(24).setCellValue((String)data.get("LANGUAGE")); 
						 onerow.createCell(25).setCellValue((String)data.get("USERSUBJECT")); 
						 onerow.createCell(26).setCellValue((String)data.get("CASTR"));
						 onerow.createCell(27).setCellValue(String.valueOf(data.get("ID"))); 
						 onerow.createCell(28).setCellValue((String)data.get("BOOKNAME")); 
						 onerow.createCell(29).setCellValue((String)data.get("TCMNAME")); 
						 onerow.createCell(30).setCellValue((String)data.get("ORIGINALTEXT")); 
						 onerow.createCell(31).setCellValue((String)data.get("VOLUMESECTION")); 
						 onerow.createCell(32).setCellValue((String)data.get("BOOKVERSION")); 
						 onerow.createCell(33).setCellValue((String)data.get("INPUTUSER")); 
						 onerow.createCell(34).setCellValue((String)data.get("INPUTDATE")); 
						 onerow.createCell(35).setCellValue((String)data.get("BOOKCD"));  
 				 }	
				 String tempFilepath = SystemUtil.getWebappRoot().toString();
				 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 System.out.println("tempFilepath::" + tempFilepath );
				 File tempfile = new File(tempFilepath);
				 if(!tempfile.exists()){
					 tempfile.mkdirs();
				 }
				 String destfile = tempFilepath + "/" + "冠心病导出数据.xls";
				 FileOutputStream fileOut = new FileOutputStream(destfile); 
				 wb.write(fileOut); 
				 fileOut.close();
				 message = destfile;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return message;
		
	}
	/**
	 * 生成题录数据文件（TXT）
	 * @return 生成的文件的路径
	 */
	public String exportTxtData(String rids){
		String message = "false";
		 try {
			 String tempFilepath = SystemUtil.getWebappRoot().toString();
			 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
			 System.out.println("tempFilepath::" + tempFilepath );
			 File tempfile = new File(tempFilepath);
			 if(!tempfile.exists()){
				 tempfile.mkdirs();
			 }
			 String destfile = tempFilepath + "/" + "export"+System.currentTimeMillis()+".txt";
			 FileOutputStream outSTr = null;      
			 BufferedOutputStream Buff = null;    
			      
			 String tab = "  ";      
			 String enter = "\r\n";      
			 List  accList = DBMgr.getDbUtilInst().queryList("select * from CHD_PAPERINFO where id in("+rids+") order by id",null);

			   StringBuffer write ;      
			    try {      
			        outSTr = new FileOutputStream(new File(destfile));      
			        Buff = new BufferedOutputStream(outSTr);      
			        for(int i=0; i<accList.size(); i++){
						Map data = (Map)accList.get(i);      
			            write = new StringBuffer(); 
			            String temp1 = null2str((String)data.get("CLASSNO"));
			            if(!"".equals(temp1))
			            	write.append("分类号:"+temp1+enter); 
			            String temp2 = null2str((String)data.get("TITLE"));
			            if(!"".equals(temp2))
			            	write.append("标题:"+temp2+enter); 
			            String temp3 = null2str((String)data.get("AUTHOR"));
			            if(!"".equals(temp3))
						write.append("作者:"+temp3+enter);
			            String temp4 = null2str((String)data.get("AUTHORUNIT"));
			            if(!"".equals(temp4))
			            	write.append("作者单位:"+temp4+enter);
			            String temp5 = null2str((String)data.get("AREASTR"));
			            if(!"".equals(temp5))
						write.append("国家\\省市:"+temp5+enter);
			            String temp6 = null2str((String)data.get("CWNUM"));
			            if(!"".equals(temp6))
			            	write.append("参文数:"+temp6+enter);
			            String temp7 = null2str((String)data.get("PERIODICALNAME"));
			            if(!"".equals(temp7))
						    write.append("刊名:"+temp7+enter);
			            String temp8 = null2str((String)data.get("YEARSTR"));
			            if(!"".equals(temp8))
			            	write.append("年份:"+temp8+enter);
			            String temp9 = null2str((String)data.get("VOLUME"));
			            if(!"".equals(temp1))
						write.append("卷:"+temp9+enter);
			            String temp10 = null2str((String)data.get("PERIOD"));
			            if(!"".equals(temp10))
						write.append("期:"+temp10+enter); 
			            String temp11 = null2str((String)data.get("PAGENO"));
			            if(!"".equals(temp11))
			            	write.append("页码:"+temp11+enter);
			            String temp12 = null2str((String)data.get("ISSNSTR"));
			            if(!"".equals(temp12))
			            	write.append("ISSN:"+temp12+enter); 
			            String temp13 = null2str((String)data.get("CONTRYCODE"));
			            if(!"".equals(temp13)) 
			            	write.append("国别:"+temp13+enter);
			            String temp14 = null2str((String)data.get("CODESTR"));
			            if(!"".equals(temp14))  
			            	write.append("地区:"+temp14+enter);
			            String temp15 = null2str((String)data.get("PUBLISHAREA"));
			            if(!"".equals(temp15)) 
						write.append("出版地:"+temp15+enter);
			            String temp16 = null2str((String)data.get("KEYWORD"));
			            if(!"".equals(temp16)) 
						write.append("关键词:"+temp16+enter);
			            String temp17 = null2str((String)data.get("SUBJECTWORD"));
			            if(!"".equals(temp17)) 
						write.append("主题词:"+temp17+enter);
			            String temp18 = null2str((String)data.get("IMPRESSWORD"));
			            if(!"".equals(temp18)) 
						write.append("特征词:"+temp18+enter);
			            String temp19 = null2str((String)data.get("UPDATEDATE"));
			            if(!"".equals(temp19)) 
						write.append("更新日期:"+temp19+enter);
			            String temp20 = null2str((String)data.get("TITLEN"));
			            if(!"".equals(temp20)) 
			            	write.append("英文标题:"+temp20+enter);
			            String temp21 = null2str((String)data.get("ABSTRACT"));
			            if(!"".equals(temp21)) 
						write.append("摘要:"+temp21+enter);
			            String temp22 = null2str((String)data.get("AUTHORABSTRACT"));
			            if(!"".equals(temp22)) 
						write.append("著者文摘:"+temp22+enter);
			            String temp23 = null2str((String)data.get("DOCUMENTTYPE"));
			            if(!"".equals(temp23)) 
						write.append("文献类型:"+temp23+enter);
			            String temp24 = null2str((String)data.get("FUNDNAME"));
			            if(!"".equals(temp24)) 
						write.append("基金:"+temp24+enter);
			            String temp25 = null2str((String)data.get("LANGUAGE"));
			            if(!"".equals(temp25)) 
						write.append("语种:"+temp25+enter);
			            String temp26 = null2str((String)data.get("USERSUBJECT"));
			            if(!"".equals(temp26)) 
						write.append("人名主题:"+temp26+enter);
			            String temp27 = null2str((String)data.get("CASTR"));
			            if(!"".equals(temp27)) 
						write.append("CA:"+temp27+enter);
			            String temp28 = null2str((String)data.get("BOOKNAME"));
			            if(!"".equals(temp28)) 
						write.append("书籍名称:"+temp28+enter); 
			            String temp29 = null2str((String)data.get("TCMNAME"));
			            if(!"".equals(temp29)) 
						write.append("中医病名:"+temp29+enter);
			            String temp30 = null2str((String)data.get("ORIGINALTEXT"));
			            if(!"".equals(temp30)) 
						write.append("原文文本化:"+temp30+enter);
			            String temp31 = null2str((String)data.get("VOLUMESECTION"));
			            if(!"".equals(temp31)) 
						write.append("卷册章节:"+temp31+enter);
			            String temp32 = null2str((String)data.get("BOOKVERSION"));
			            if(!"".equals(temp32)) 
						write.append("书籍版本:"+temp32+enter);
			            String temp33 = null2str((String)data.get("INPUTUSER"));
			            if(!"".equals(temp33)) 
						write.append("录入人:"+temp33+enter);
			            String temp34 = null2str((String)data.get("INPUTDATE"));
			            if(!"".equals(temp34)) 
					    write.append("录入日期:"+temp34+enter); 
			            String temp35 = null2str((String)data.get("BOOKCD"));
			            if(!"".equals(temp35)) 
					    write.append("朝代:"+temp35+enter);      
			            write.append(enter);          
			            Buff.write(write.toString().getBytes("UTF-8")); 
			            
			        }             
			        Buff.flush();      
			        Buff.close();      
			  } catch (Exception e) {      
			        e.printStackTrace();      
			    } finally {      
			        try {      
			           Buff.close();      
			            outSTr.close();      
			        } catch (Exception e) {      
			           e.printStackTrace();      
			        }      
			    }       
				 message = destfile;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return message;
		
	}
	private String null2str(String content){
		if(null == content || "null".equalsIgnoreCase(content)){
			return "";
		}
		return content;
	}
	
	 private static String cutStr(String str){
		 if(str.lastIndexOf(',') != -1){
			 str = str.substring(0, str.length()-1);
		 }
		 return str;
	 }
}
